<template>
  <el-select
    v-model="selectValue"
    clearable
    placeholder="请选择"
    @clear="clear"
  >
    <el-input
      v-model="filterText"
      class="selectInput"
      :placeholder="placeholder"
    />
    <el-option :value="optionValue" style="height: auto" class="select-tree" :label="optionLabel">
      <el-tree
        ref="tree"
        :data="tree"
        node-key="id"
        highlight-current
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        :props="defaultProps"
        @node-click="handleNodeClick"
      />
    </el-option>
  </el-select></template>

<script>

export default {
  name: 'SelectTree',
  props: {
    parentId: {
      type: Number,
      default: null
    },
    tree: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectValue: null,
      optionValue: null,
      optionLabel: '',
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    parentId(val) {
      if (val) {
        // eslint-disable-next-line no-return-assign
        this.selectValue = val
        this.optionValue = val
        const values = []
        this.findById(val, this.tree, values)
        if (values.length > 0) {
          this.optionLabel = values[0].label
        }
      } else {
        this.selectValue = null
        this.optionValue = null
        this.optionLabel = ''
      }
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(data) {
      this.optionLabel = data.label
      this.selectValue = data.id
      this.optionValue = data.id
      this.$emit('update:parentId', data.id)
    },
    clear() {
      this.optionLabel = ''
      this.selectValue = null
      this.optionValue = null
      this.$refs.tree.setCurrentKey(null)
      this.$emit('update:parentId', null)
    },

    findById(id, tree, values) {
      for (const val of tree) {
        if (val.id === id) {
          values.push(val)
          break
        }
        if (val.children) {
          this.findById(id, val.children, values)
        }
      }
    }

  }
}
</script>

<style scoped>
.icon-label{
  margin-left: 1vh;
}
.el-input-number--medium{
  width: 100%;
}

.select-tree{
  padding: 0 0;
}
.selectInput{
  padding: 10px;
}
</style>
